package com.lanou.userLogin.book.dao;

import com.lanou.userLogin.book.domain.Book;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BookDaoImpl implements BookDao {

    private ComboPooledDataSource dataSource = new ComboPooledDataSource();

    @Override
    public List<Book> findAllBook(){
        try {
            Connection conn = dataSource.getConnection();
            QueryRunner qr = new QueryRunner();
            List<Book> query = qr.query(conn, "select * from book join category on book.cid = category.cid", new BeanListHandler<Book>(Book.class));
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    @Override
    public List<Book> findAllBookByCname(String cname) {
        try {
            Connection conn = dataSource.getConnection();
            QueryRunner qr = new QueryRunner();
            List<Book> query = qr.query(conn, "select * from book join category on book.cid = category.cid where cname = ?", new BeanListHandler<Book>(Book.class),cname);
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    @Override
    public List<Book> oneBookInfo(String bid){
        try {
            Connection conn = dataSource.getConnection();
            QueryRunner qr = new QueryRunner();
            List<Book> query = qr.query(conn, "select * from book where bid = ?", new BeanListHandler<Book>(Book.class), bid);
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new ArrayList<>();
    }

    @Override
    public Book oneBook(String bid) {
        try {
            Connection conn = dataSource.getConnection();
            QueryRunner qr = new QueryRunner();
            Book query = qr.query(conn, "select * from book where bid = ?", new BeanHandler<Book>(Book.class), bid);
            return query;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return new Book();
    }
}
